package com.cbdp.common.handler;

import com.cbdp.common.exception.BizException;
import com.cbdp.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * com.cbdp.admin.handler
 *
 * @author 白雨浓
 * date: 2018/10/26 11:44
 * content:
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 参数异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleException(MethodArgumentNotValidException e) {
        var result = e.getBindingResult();
        if (result.hasErrors() && result.getAllErrors().size() > 0) {
            var error = result.getAllErrors().get(0);
            return new Result(HttpStatus.BAD_REQUEST.value(), error.getDefaultMessage());
        }
        return new Result(HttpStatus.BAD_REQUEST.value(), null);
    }

    /**
     * 业务异常处理
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public Result handle(BizException e) {
        return new Result(e.getCode(), e.getMessage());
    }

    /**
     * 未知异常处理
     */
    @ExceptionHandler(value = Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handle(Throwable t) {
        t.printStackTrace();
        log.error("未知错误:", t);
        return new Result(-999, "系统忙，请稍后重试");
    }

}
